<template>
  <div class="border padding">
    <t-upload
      v-model="files"
      :multiple="props.multiple"
      :tips="props.tips"
      :action="uploadApiUrl + '/upload/index/file'"
      :headers="defaultHeader"
      :format-response="formatResponse"
      theme="custom"
      :accept="props.accept"
      :max="props.max"
      :sizeLimit="props.sizeLimit"
    >
      <slot name="btn">
        <t-button theme="default">上传图标</t-button>
      </slot>
    </t-upload>
    <ul class="file-list" v-if="files && files.length">
      <li v-for="(item, index) in files" :key="index">
        <div class="text">
          <t-image-viewer :images="[uploadApiUrl + item.url]">
            <template #trigger="{ open }: any">
              <img
                :src="uploadApiUrl + item.url"
                width="20"
                height="20"
                class="margin-right-xs"
                v-if="item.url != undefined"
                @click="open"
              />
            </template>
          </t-image-viewer>
          {{ item.name }}
        </div>
        <div class="status">
          <template v-if="item.status === 'waiting'">
            <component is="LoadingIcon" size="20" />
          </template>
          <template v-else-if="item.status === 'process'">
            <span class="text-caption">{{ item.percent }}</span>
          </template>
          <template
            v-else-if="
              item.status === 'success' &&
              item.response &&
              item.response.code != 0
            "
          >
          <component is="ErrorCircleFilledIcon" class="color-error" size="20" />
          </template>
          <template v-else>
            <component is="CheckCircleFilledIcon" class="color-success" size="20" />
          </template>
          <component is="CloseCircleFilledIcon" class="color-primary hover-icon" size="20" @click="deleteFile(index)" />
        </div>
      </li>
    </ul>
  </div>
</template>
<script lang="ts" setup>
import { ref, onBeforeMount } from 'vue';
import { useUserStore } from '@/store/modules/user';
import { MessagePlugin } from 'tdesign-vue-next';

const uploadApiUrl = import.meta.env.VITE_API_URL;
const userStore = useUserStore();

const files = ref<{ [key: string]: any }[]>([]);
const defaultHeader = { from: 'api', token: userStore.token };

interface UploadFileProps {
  fileUrl?: string | undefined; // 图片地址
  tips?: string; //文本提示 => 非必传
  dataHeader?: {
    [propName: string]: string;
  }; //上传的请求头部 => 非必传
  fileType?: string[]; //文件类型限制
  accept?: string; // 接受上传的文件类型
  max?: number; // 上传数量
  multiple?: boolean; // 是否支持多文件上传
  sizeLimit?: { size: number; unit: string }; // 大小限制
}

// 接受父组件参数，配置默认值
const props = withDefaults(defineProps<UploadFileProps>(), {
  dataHeader: () => ({}),
});

onBeforeMount(async () => {
  Object.assign(defaultHeader, props.dataHeader ?? {});
  if (props.fileUrl && props.fileUrl.length) {
    files.value.push({
      status: 'success',
      name: props.fileUrl.substring(
        props.fileUrl.lastIndexOf('/') + 1,
        props.fileUrl.length,
      ),
      url: props.fileUrl,
    });
  }
});

interface UploadEmits {
  (e: 'update:fileUrl', value: string): void;
}
const emit = defineEmits<UploadEmits>();

function formatResponse(res: any) {
  if (res.code == 0) {
    let fileInfo = res.data;
    let img = fileInfo['thumb1'] ? fileInfo['thumb1'] : fileInfo['file_path'];
    res.url = img;
    emit('update:fileUrl', img);
  } else {
    MessagePlugin.error('上传文件出错：' + res.msg);
  }
  return res;
}

const deleteFile = (index: number) => {
  files.value.splice(index, 1);
  emit('update:fileUrl', '');
};
</script>
<style lang="scss" scoped>
.file-list {
  display: flex;
  flex-direction: column;
  margin-top: 16px;

  > li {
    display: flex;
    flex: 1;
    justify-content: space-between;
    align-items: center;

    & + li {
      margin-top: 16px;
    }

    .text {
      display: flex;
      align-items: center;
    }

    .status {
      @extend .text;
    }

    .hover-icon {
      display: none;
    }

    &:hover {
      .hover-icon {
        display: block;
        cursor: pointer;
      }

      .t-icon:not(.hover-icon) {
        display: none;
      }
    }
  }
}
</style>
